package com.sojson.config.mybatis.injector.impl;

import java.sql.SQLException;
import java.util.List;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.sojson.enums.EDbType;
import com.sojson.project.addr.entity.bo.Point;
import com.sojson.util.ExpUtil;
import com.sojson.util.db.DbUtil;

/**
 * 自定义全局注入逻辑抽象类
 * 
 * @author liu
 * @date 2022-01-21
 */
public abstract class CustomAbbstractMethod extends AbstractMethod {

    /***/
    private static final long serialVersionUID = 1L;

    /**
     * Sql转换器
     * 
     * @param tableInfo
     * @param sql
     * @param formatSql
     * @return
     */
    public String fieldProcess(TableInfo tableInfo, String sql, String formatSql) {
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        try {
            for (TableFieldInfo tableFieldInfo : fieldList) {

                // 转换坐标
                sql = point(tableFieldInfo, sql, formatSql);

            }
        } catch (Exception e) {
            ExpUtil.throwEx(e);
        }
        return sql;
    }

    /**
     * 坐标转换器
     * 
     * @param tableFieldInfo
     * @param sql
     * @param formatSql
     * @return
     * @throws SQLException
     */
    private String point(TableFieldInfo tableFieldInfo, String sql, String formatSql) throws SQLException {
        Class<?> propertyType = tableFieldInfo.getPropertyType();
        if (!Point.class.equals(propertyType)) {
            return sql;
        }

        String gonel = String.format(formatSql, tableFieldInfo.getProperty());
        String dbType = DbUtil.getDBType();
        if (EDbType.MYSQL.getName().equals(dbType)) {
            sql = sql.replace(gonel, String.format("ST_GeomFromText(CONCAT(CONCAT('POINT(',%s),')'))", gonel));
        } else if (EDbType.ORACLE.getName().equals(dbType)) {
            sql = sql.replace(gonel, String.format("sdo_geometry( 'POINT ('|| %s ||')',8307)", gonel));
        } else if (EDbType.DB2.getName().equals(dbType)) {
            sql = sql.replace(gonel, String.format("DB2GSE.ST_POINT(CONCAT(CONCAT('POINT (',%s),')'), 1)", gonel));
        }
        return sql;
    }

}